package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.MyResponseResult;
import com.itheima.utils.MyJwtUtils;
import com.itheima.utils.MyThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class MyLonigInterceptor implements HandlerInterceptor {

    @Autowired
    private MyJwtUtils myJwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Token");
        Map<String, Object> map = myJwtUtils.parseJwt(token);
        if(map==null){
            MyResponseResult<Object> result = MyResponseResult.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(result);
            response.getWriter().print(jsonString);
            return false;
        }
        //合法
        MyThreadLocalUtils.setValue(map);
        return true;
    }
}
